package de.recipeminer.persistence;

import com.db4o.ObjectSet;
import org.apache.log4j.Logger;

/**
 * @author Markus Ackermann
 */
public class Db4oObjectCompanion<T extends Db4oCompanionProvider<T>> {
    private static Logger logger = Logger.getLogger(Db4oObjectCompanion.class);
    private T object;

    public Db4oObjectCompanion(T object) {
        this.object = object;
    }

    public ObjectSet<T> getAll() {
        Db4oContainer container = Db4oContainers.getDefault();
        return container.query((Class<T>) object.getClass());
    }

    public void save() {
        
        if(!object.validate()) {
            String msg = String.format("Persistence error: Validation failed for object %s (%s) " +
                    "while attempting to save it.");
            throw new IllegalStateException(msg);    
        }

        Db4oContainer container = Db4oContainers.getDefault();
        T storedObject = null;
        if (!container.ext().isStored(this)) {
            ObjectSet<T> knownSimilar = container.queryByExample(object);
       switch (knownSimilar.size()){
                case 0: storedObject = null; break;
                case 1: storedObject = knownSimilar.get(0); break;
                default: throw new IllegalStateException("Multiple stored identitiy candidates");
            }
        }
        if(storedObject != null && storedObject != object){
            container.delete(storedObject);
        }
            container.store(object);
            container.commit();
        }

}
